<?php namespace App\Admin\Access\Role\Services;

use App\Admin\Access\OperationGroup\Repository as OperationGroupRepository;
use Input;

trait OperationManage {
    
    //获取角色信心（包含操作）
	public function getOperations(){
        $role = $this->repository->addCriteria($this->getIndexCriteria())->first();
		if(!$role){//结果不存在
            return $this->inputError('角色不存在');
		}
        return $this->success($this->getOperationsWithChecked($role));
	}
    
    //修改角色操作
	public function changeOperations(){
        $role = $this->repository->addCriteria($this->getIndexCriteria())->first();
		if(!$role){//结果不存在
            return $this->inputError('角色不存在');
		}
		//参数构造
		$operationIds = array_filter(explode(',', Input::get('operation_ids', '')), 'is_numeric');
		$dataIdsRaw = Input::get('data_ids', '');
        $dataIds = [];
        $dataIdTemp = $dataIdsRaw ? explode('|', $dataIdsRaw) : [];
        foreach($dataIdTemp as $item){
            $itemTemp = explode(':', $item);
            if(count($itemTemp) !== 2){
                return $this->inputError('数据格式有误');
            }
            $groupId = $itemTemp[0];
            if(strpos($groupId, '_') !== 0){
                return $this->inputError('数据格式有误');
            }
            if(!is_numeric(str_replace('_', '', $groupId))){
                return $this->inputError('数据格式有误');
            }
            $groupData = array_filter(explode(',', $itemTemp[1]), 'is_numeric');
            if(count($groupData) < 1){
                return $this->inputError('数据格式有误');
            }
            $dataIds[$groupId] = $groupData;
        }
        //权限越级分配校验
        if($role->parent_id == '0'){
            $parent = false;
        }else{
            $parent = $this->repository->getModel()->find($role->parent_id);
            if(!$parent){
                return $this->inputError('数据格式有误');
            }
        }
        $operationGroup = new OperationGroupRepository();
        $parentOperationsRaw = $operationGroup->getByRoleWithOperations($parent);
        $parentOperationIds = [];
        $parentDataIds = [];
        foreach($parentOperationsRaw as $group){
            $groupId = $group->group_id;
            $operationsRaw = $group->operations;
            $operationIdsTemp = [];
            foreach($operationsRaw as $operation){
                $operationIdsTemp[] = $operation->key;
            }
            if($group->type == '1'){
                $parentOperationIds = array_merge($parentOperationIds, $operationIdsTemp);
            }else if($group->type == '2'){
                $parentDataIds['_'.$groupId] = $operationIdsTemp;
            }
        }
        foreach($operationIds as $operationId){
            if(!in_array($operationId, $parentOperationIds)){
                return false;
            }
        }
        foreach($dataIds as $groupId => $dataIdsArr){
            if(!isset($parentDataIds[$groupId])){
                return false;
            }
            foreach($dataIdsArr as $dataId){
                if(!in_array($dataId, $parentDataIds[$groupId])){
                    return false;
                }
            }
        }
        try {
            $this->repository->resetCriteria()->addCriteria($this->getIndexCriteria());
            $this->repository->update([
                'operation_ids' => implode(',', $operationIds),
                'extension' => $dataIds ? $this->repository->getModel()->encodeExtension($dataIds) : ''
            ]);
            return $this->success();
		} catch (\Exception $ex) {
            return $this->sysError($ex);
		}
	}

    //获取给定角色的所有操作并作归属校验
	protected function getOperationsWithChecked($role){
        $operationGroup = new OperationGroupRepository();
        $currentOperationsRaw = $operationGroup->getByRoleWithOperations($role);
        $current = [];
        foreach($currentOperationsRaw as $item){
            $groupId = $item->group_id;
            $operationsRaw = $item->operations;
            $operations = [];
            foreach($operationsRaw as $operation){
                $operations['_'.$operation->key] = '';
            }
            $current['_'.$groupId] = $operations;
        }
        $parentOperations = [];
		if($role->parent_id == '0'){
            $parentOperations = $operationGroup->getByRoleWithOperations();
        }else{
            $parent = $this->repository->getModel()->find($role->parent_id);
            if($parent){
                $parentOperations = $operationGroup->getByRoleWithOperations($parent);
            }
        }
        //填充选中状态
        foreach($parentOperations as $group){
            foreach($group->operations as $operation){
                $operation->selected = isset($current['_'.$group->group_id]['_'.$operation->key]) ? 1 : 0;
            }
        }
        return $parentOperations;
	}
}